package com.zhouheng.common.filestore.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FileStoreConfig {

    @Bean
    @ConfigurationProperties(prefix = "filestore")
    public FileStoreProperties fileStoreProperties() {
        return new FileStoreProperties();
    }

    @Bean
    public MinioClient minioClient(FileStoreProperties fileStoreProperties) throws Exception {
        MinioClient client = MinioClient.builder()
                .endpoint(fileStoreProperties.getEndpoint())
                .credentials(fileStoreProperties.getAccessKey(), fileStoreProperties.getSecretKey())
                .build();

        String bucket = fileStoreProperties.getBucket();
        boolean bucketExists =
                client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!bucketExists) {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucket).objectLock(true).build());
        }

        return client;
    }
}
